<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Db;
use think\Exception;

class Message
{
    public function getMessageList($current_page,$page_num,$where)
    {
        $data = Db::name("message")
            ->field("m_id,title,content,create_time,exm_status,og_id,class_type")
            ->where($where)
            ->page($current_page,$page_num)
            ->order("update_time desc")
            ->select();
        $total_num = Db::name("message")
             ->where($where)
            ->count();
        $list['current_page'] = $current_page;
        $list['total_page'] = ceil($total_num / $page_num);
        $list['page_num'] = $page_num;
        $list['total_num'] = $total_num;
        $list['data'] = $data;
        return $list;
    }

    /**
     * 会员商品升级审核
     */
    public function examineGrade($input){
        $member_id=$input['member_id'];
        $og_id=Db::name("message")->where(['m_id'=>$input['m_id']])->value("og_id");//获取订单商品ID 需要升级
        if(!empty($og_id)){
            $order=Db::name("order")->alias("o")
                ->join("mm_order_goods og",'og.order_id=o.order_id')
                ->join("mm_goods_info gn",'gn.goods_id=og.goods_id')
                ->where(['og.og_id'=>$og_id])
                ->field("o.source_type,o.member_id,og.*,gn.copper_money,gn.silver_money,gn.gold_money")
                ->find();
            $source_type=$order['source_type'];
            //获取当前订单升级等级
            $orderAmount=$order['score_money']*$order['goods_num'];
            $copper_money=$order['copper_money'];
            $silver_money=$order['silver_money'];
            $gold_money=$order['gold_money'];

            if ($orderAmount >= $gold_money&&$gold_money>0) {
                $new_goods_member_grade = 4;
            } elseif ($orderAmount >= $silver_money&&$silver_money>0) {
                $new_goods_member_grade = 3;

            } elseif ($orderAmount >= $copper_money&&$copper_money>0) {
                $new_goods_member_grade = 2;
            } else {
                $new_goods_member_grade= 1;
            }
            $tm=time();

            if( $source_type==4){ //干货分享的裂变爆品
                Db::startTrans();
                try{
                    if( $new_goods_member_grade>1){
                        //分销
                        $dstList=Db::name("distribution_order_goods")
                            ->where(['dst_status'=>['in',[2,4]],'is_real'=>2,'goods_id'=>$order['goods_id'],
                            'dst_member_id'=>$order['member_id'],'dst_min_grade'=>['elt',$new_goods_member_grade]])
                            ->select();
                        $dstAtt=[];
                        if(!empty($dstList)){
                            foreach ($dstList as $dst) {
                                $dstAtt[]=$dst['dst_id'];
                                //直接分销
                                $ogInfo = Db::name("order_goods")->where(['og_id' => $dst['order_goods_id']])->find();
                                if ($new_goods_member_grade == 4) {//金客
                                    $rate = $ogInfo['golden'];
                                } elseif ($new_goods_member_grade == 3) {//银客
                                    $rate = $ogInfo['silver'];
                                } elseif ($new_goods_member_grade == 2) {//铜客
                                    $rate = $ogInfo['copper'];
                                }
                                $direct_push_score = ($ogInfo['score_money'] * $ogInfo['goods_num'] + $ogInfo['coin_money'] * $ogInfo['goods_num']) * $rate / 100;
                                $asset_log = ['member_id' => $order['member_id'], 'type' => 1, 'amount' => $direct_push_score,
                                    'source_type' => 2, 'description' => "商城消费推荐奖", "change_type" => 1, 'log_type_id' => 5,
                                    'relation_id' => $order['order_id'], 'relation_sid' => $og_id, 'create_time' => $tm, 'update_time' => $tm, 'handle_type' => 6, 'release_status' => 0];
                                $num = Db::name("member_asset_log")->insert($asset_log);
                                if ($num <= 0) {
                                    throw new Exception("更新失败1");
                                }
                                $num = Db::name("member_asset")->where(['member_id' => $order['member_id']])->setInc("frozen_score", $direct_push_score);
                                if ($num <= 0) {
                                    throw new Exception("更新失败2");
                                }
                            }
                            if(!empty($dstAtt)){
                                $num=Db::name("distribution_order_goods")->where(['dst_id'=>['in',  $dstAtt]])->update(['dst_grade'=>$new_goods_member_grade,'dst_status'=>1]);//已分销
                                if($num<=0){
                                    throw new Exception("更新失败3");
                                }
                            }
                        }
                        //升级
                        $num = Db::name("goods_member_grade")->insert(['member_id' => $order['member_id'],'goods_id'=>$order['goods_id'],
                            'member_grade'=>$new_goods_member_grade,'update_time'=>$tm,'create_time'=>$tm]);
                        if ($num <= 0) {
                            throw new Exception("更新失败4");
                        }
                        //更新审核时间
                        $num=Db::name("distribution_order_goods")->where(['order_goods_id'=>$og_id,'is_grade'=>1,'member_id' => $order['member_id'],'dst_member_id'=>$member_id])->update(['exm_time'=>$tm]);

                        if ($num <= 0) {
                            throw new Exception("更新失败5");
                        }
                    }
                    Db::commit();
                    return true;
                }catch (Exception $e){
                    Db::rollback();
                    dump($e->getMessage());exit;
                    returnJson(-2004,"操作失败");
                }
            }else{ //联盟商家列表爆品
                if( $new_goods_member_grade>1){
                    Db::startTrans();
                    try{
                        //升级 不能直接审核 原计划收货收7天进行升级
//                        $num = Db::name("goods_member_grade")->insert(['member_id' => $order['member_id'],'goods_id'=>$order['goods_id'],
//                            'member_grade'=>$new_goods_member_grade,'update_time'=>$tm,'create_time'=>$tm]);
//                        if ($num <= 0) {
//                            throw new Exception("更新失败4");
//                        }
                        //更新审核时间
                        $num=Db::name("distribution_order_goods")->where(['order_goods_id'=>$og_id,'is_grade'=>1,'member_id' => $order['member_id'],'dst_member_id'=>$member_id])->update(['exm_time'=>$tm]);
                        if ($num <= 0) {
                            throw new Exception("更新失败4");
                        }
                        Db::commit();
                        return true;
                    }catch (Exception $e){
                        Db::rollback();
                        returnJson(-2004,"操作失败");
                    }
                }
            }

        }
    }

    /**
     * 我的消息页面---每个分类是否有新消息的状态
     */
    public function getNew($member_id){
        //查询用户注册时间
        $create_time=Db::name('member')->where('member_id',$member_id)->value('create_time');

        //系统消息
        $system_count=$this->isHaveNew($member_id,$create_time,14);
        if($system_count>0){
            $data['system_hot']=1;//有未读消息
        }else{
            $data['system_hot']=2;//没有未读消息
        }

        //联盟商家
        $store_count=$this->isHaveNew($member_id,$create_time,13);
        if($store_count>0){
            $data['store_hot']=1;
        }else{
            $data['store_hot']=2;
        }

        //人才展厅
        $personal_count=$this->isHaveNew($member_id,$create_time,2);
        if($personal_count>0){
            $data['personal_hot']=1;
        }else{
            $data['personal_hot']=2;
        }

        //企业展厅
        $enterprise_count=$this->isHaveNew($member_id,$create_time,1);
        if($enterprise_count>0){
            $data['enterprise_hot']=1;
        }else{
            $data['enterprise_hot']=2;
        }

        //征婚交友
        $marriage_count=$this->isHaveNew($member_id,$create_time,3);
        if($marriage_count>0){
            $data['marriage_hot']=1;
        }else{
            $data['marriage_hot']=2;
        }

        //短租员工
        $short_count=$this->isHaveNew($member_id,$create_time,4);
        if($short_count>0){
            $data['short_hot']=1;
        }else{
            $data['short_hot']=2;
        }

        //我要兼职
        $staff_count=$this->isHaveNew($member_id,$create_time,5);
        if($staff_count>0){
            $data['staff_hot']=1;
        }else{
            $data['staff_hot']=2;
        }

        //兼职招募
        $recruit_count=$this->isHaveNew($member_id,$create_time,6);
        if($recruit_count>0){
            $data['recruit_hot']=1;
        }else{
            $data['recruit_hot']=2;
        }

        //投资意向
        $invest_count=$this->isHaveNew($member_id,$create_time,7);
        if($invest_count>0){
            $data['invest_hot']=1;
        }else{
            $data['invest_hot']=2;
        }

        //股东招募
        $partner_count=$this->isHaveNew($member_id,$create_time,8);
        if($partner_count>0){
            $data['partner_hot']=1;
        }else{
            $data['partner_hot']=2;
        }

        //加盟代理
        $join_count=$this->isHaveNew($member_id,$create_time,9);
        if($join_count>0){
            $data['join_hot']=1;
        }else{
            $data['join_hot']=2;
        }

        //联合办公
        $union_count=$this->isHaveNew($member_id,$create_time,10);
        if($union_count>0){
            $data['union_hot']=1;
        }else{
            $data['union_hot']=2;
        }

        //企业招聘
        $business_count=$this->isHaveNew($member_id,$create_time,11);
        if($business_count>0){
            $data['business_hot']=1;
        }else{
            $data['business_hot']=2;
        }

        //采购邀标
        $purchase_count=$this->isHaveNew($member_id,$create_time,12);
        if($purchase_count>0){
            $data['purchase_hot']=1;
        }else{
            $data['purchase_hot']=2;
        }

        return $data;
    }

    /**
     * 我的消息---快速处理---------要传入class_type和发消息给我的人
     *      type  1=全部  2=别人发给我  3=我发给别人
     *   class_type  1企业展厅,2人才展厅,3征婚,4短租员工,5我要兼职,6兼职招募,7投资意向,8股东招募,
     *          9加盟代理,10联合办公,11企业招募,12采购邀标,13联盟商城 14系统消息
     *   user_id  发消息给我的人或者我发消息的人
     */
    public function msgList($type,$page,$page_size,$class_type,$member_id,$user_id){
        //dump($member_id);
        //查询用户注册时间
        $create_time=Db::name('member')->where('member_id',$member_id)->value('create_time');

        $p = $page;
        $listPages = $page_size;
        $page = ($p-1)*$listPages;

        $sql = "SELECT `m_id`,`title`,`create_time`,`content`,
(SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id  ) as is_read FROM `mm_message` m

WHERE   `create_time` > ".$create_time." AND (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0

AND ";
        if($type==1){
            $sql .= " ( ( FIND_IN_SET(". $member_id.",object_arr) and (`member_id` =".$user_id.") )
              or ( (`member_id` =".$member_id.") and FIND_IN_SET(". $user_id.",object_arr)) ";
        }elseif($type==2){
            $sql .= " ( FIND_IN_SET(". $member_id.",object_arr) and `member_id` =".$user_id;
        }else{
            $sql .= " (`member_id` =".$member_id." and FIND_IN_SET(". $user_id.",object_arr) " ;
        }
        $sql .= " ) and class_type=".$class_type;
        $sql .= " ORDER BY `create_time` DESC limit $page,$listPages";

        $sql_count = "SELECT count(*) FROM `mm_message` m
WHERE   `create_time` >".$create_time." AND  (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0
AND ";
        if($type==1){
            $sql_count .= " ( ( FIND_IN_SET(". $member_id.",object_arr) and (`member_id` =".$user_id.") )
              or ( (`member_id` =".$member_id.") and FIND_IN_SET(". $user_id.",object_arr)) ";
        }elseif($type==2){
            $sql_count .= " ( FIND_IN_SET(". $member_id.",object_arr) and `member_id` =".$user_id;
        }else{
            $sql_count .= " (`member_id` =".$member_id." and FIND_IN_SET(". $user_id.",object_arr) " ;
        }
        $sql_count .= ") and class_type=".$class_type;
        //dump($sql);

        //查询未读的总条数
        $sql_count2 = "SELECT count(*) FROM `mm_message` m
        WHERE  `create_time` >".$create_time." 
        AND ( (FIND_IN_SET(". $member_id.",object_arr) and (`member_id` =".$user_id.") ) or 
        ((`member_id` =".$member_id.")  and FIND_IN_SET(". $user_id.",object_arr))";
        $sql_count2 .= ") AND  (SELECT COUNT(um.id) FROM mm_message_user um 
            WHERE um.member_id =".$member_id." AND um.mes_id = m.m_id AND (um.is_delete = 1 OR um.is_read =1)  )=0
            and class_type = ".$class_type ;

        $count2 = Db::query($sql_count2);

        $count = Db::query($sql_count);
        $count = $count[0]['count(*)'];
        $list =  Db::query($sql);

        //echo db()->getLastSql(); exit;
        $totalPage = ceil($count/$listPages);

        $data['current_page'] = $p;
        $data['total_page'] =$totalPage;
        $data['page_num'] = $page_size;
        $data['total_num'] = $count;
        $data['data'] = $list;
        $data['count2'] =$count2[0]['count(*)'];
        $data['user_id'] =$user_id;

        return $data;
    }

    /**
     * 是否有新的信息
     */
    public function isHaveNew($member_id,$create_time,$class_type){
        //查询未读的总条数
        $sql_count2 = "SELECT count(*) FROM `mm_message` m
        WHERE  `create_time` >".$create_time." 
        AND  (`object_type` = 1  OR (`object_type`=2 and FIND_IN_SET(". $member_id.",object_arr)) 
";
        $sql_count2 .= ") AND  (SELECT COUNT(um.id) FROM mm_message_user um 
            WHERE um.member_id =".$member_id." AND um.mes_id = m.m_id AND (um.is_delete = 1 OR um.is_read =1)  )=0
            and class_type = ".$class_type ;

        $count2 = Db::query($sql_count2);
        $count = $count2[0]['count(*)'];

        return $count;
    }


    /**
     * 发送消息
     */
    public function sendMsg($member_id,$data){

        $info['title']=$data['title'];
        $info['content']=$data['content'];
        $info['member_id']=$member_id;
        $info['object_type']=2;
        $info['object_arr']=$data['user_id'];
        $info['class_type']=$data['class_type'];

        Db::name('message')->insert($info);

        return true;

    }

    /**
     * 我的消息----某个分类下的列表
     */
    public function msgClassList($page,$page_size,$class_type,$member_id){
        $create_time=Db::name('member')->where('member_id',$member_id)->value('create_time');
        $p = $page;
        $listPages = $page_size;
        $page = ($p-1)*$listPages;
/*
        $sql = "SELECT `m_id`,`title`,`create_time`,`member_id`,`object_arr`,
(SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id  ) as is_read FROM `mm_message` m

WHERE   `create_time` > ".$create_time." AND (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0

AND ";*/
        $sql ="select `member_id` FROM `mm_message` m  
    WHERE   `create_time` > ".$create_time."  and " ;
        $sql .= " ( FIND_IN_SET(". $member_id.",object_arr) ";

        $sql .= " ) and class_type=".$class_type;
        $sql .= "  group by `member_id`  limit $page,$listPages";
//        dump($sql);

       /* $sql_count = "SELECT count(*) FROM `mm_message` m
WHERE   `create_time` >".$create_time." AND  (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0
AND ";*/
        $sql_count="SELECT count(*) FROM `mm_message` m
WHERE   `create_time` >".$create_time." AND   ";
        $sql_count .= " (  FIND_IN_SET(". $member_id.",object_arr)   ";

        $sql_count .= ") and class_type=".$class_type." group by `member_id` ";
        //dump($sql_count );
        $count = Db::query($sql_count);
        //echo db()->getLastSql();
        if(empty($count)){
            $count=0;
        }else{
            //$count = $count[0]['count(*)'];
            $count=(count($count));
        }

        $list =  Db::query($sql);

        //echo db()->getLastSql(); exit;
        foreach ($list as $k=>&$v){
            $user=Db::name('member')
                ->where('member_id',$v['member_id'])
                ->find();
            if(empty($user)){
                $v['nickName']='';
                $v['avatarUrl']='';
            }else{
                $v['nickName']=$user['nickName'];
                $v['avatarUrl']=$user['avatarUrl'];
            }


            $message=Db::name('message')
                ->where([Db::raw("FIND_IN_SET($member_id,object_arr)")])
                ->order('create_time desc')
                ->find();

            if($class_type==14){
                $v['intro']=$message['title'];
            }else{
                $intro=Db::name('member_info')
                    ->where('member_id',$v['member_id'])
                    ->find();
                if(empty($intro)){
                    $v['intro']='';
                }else{
                    $v['intro']=$intro['signature'];
                }
            }
            $v['create_time']=$message['create_time'];
            //未读消息条数
            $sql_count2 = "SELECT count(*) FROM `mm_message` m
        WHERE  `create_time` >".$create_time." 
        AND   ( FIND_IN_SET(". $member_id.",object_arr) and (`member_id` =".$v['member_id'].")";
            $sql_count2 .= ") AND  (SELECT COUNT(um.id) FROM mm_message_user um 
            WHERE um.member_id =".$member_id." AND um.mes_id = m.m_id AND (um.is_delete = 1 OR um.is_read =1)  )=0
            and class_type = ".$class_type ;

            $count2 = Db::query($sql_count2);
            if(empty($count2)){
                $v['count']=0;
            }else{
                $v['count']=$count2[0]['count(*)'];
            }

        }


        $totalPage = ceil($count/$listPages);

        $data['current_page'] = $p;
        $data['total_page'] =$totalPage;
        $data['page_num'] = $page_size;
        $data['total_num'] = $count;
        $data['data'] = $list;

        return $data;
    }


    /**
     * 消息详情
     */
    public function msgDetail($mid,$member_id){
        $read=Db::name('message_user')
            ->where(['member_id'=>$member_id,'mes_id'=>$mid])->find();
        if(empty($read)){
            $arr['member_id']= $member_id;
            $arr['is_read'] = 1;
            $arr['is_delete']= 0;
            $arr['mes_id'] = $mid;
            $arr['delete_time'] = 1;
            Db::name('message_user')->insert($arr);
        }
       /* $info = Db::name('message')
            ->field('m_id,title,content.create_time')
            ->where('m_id',$mid)
            ->find();

        return $info;*/
       return true;
    }

    /**
     * 系统消息分类
     */
    public function msgSystemList($page,$page_size,$member_id){
        $create_time=Db::name('member')->where('member_id',$member_id)->value('create_time');
        $p = $page;
        $listPages = $page_size;
        $page = ($p-1)*$listPages;

        $sql ="select `member_id` FROM `mm_message` m  
    WHERE   `create_time` > ".$create_time."  and " ;
        $sql .= " ( FIND_IN_SET(". $member_id.",object_arr) ";

        $sql .= " ) and class_type=14";
        $sql .= " group by `member_id`   limit $page,$listPages";
        //group by `member_id`
        //dump($sql);

        $sql_count="SELECT count(*) FROM `mm_message` m
WHERE   `create_time` >".$create_time." AND   ";
        $sql_count .= " (  FIND_IN_SET(". $member_id.",object_arr)   ";

        $sql_count .= ") and class_type=14 group by `member_id` ";
        //dump($sql_count );
        $count = Db::query($sql_count);
        //echo db()->getLastSql();
        if(empty($count)){
            $count=0;
        }else{
            $count=(count($count));
        }

        $list =  Db::query($sql);

        //echo db()->getLastSql(); exit;
        foreach ($list as $k=>&$v){

            $message=Db::name('message')
                ->where([Db::raw("FIND_IN_SET($member_id,object_arr)")])
                ->order('create_time desc')
                ->find();

            $v['title']=$message['title'];
            $v['intro']=$message['content'];

            $v['create_time']=$message['create_time'];
            //未读消息条数
            $sql_count2 = "SELECT count(*) FROM `mm_message` m
        WHERE  `create_time` >".$create_time." 
        AND   ( FIND_IN_SET(". $member_id.",object_arr) and (`member_id` =".$v['member_id'].")";
            $sql_count2 .= ") AND  (SELECT COUNT(um.id) FROM mm_message_user um 
            WHERE um.member_id =".$member_id." AND um.mes_id = m.m_id AND (um.is_delete = 1 OR um.is_read =1)  )=0
            and class_type = 14" ;

            $count2 = Db::query($sql_count2);
            if(empty($count2)){
                $v['count']=0;
            }else{
                $v['count']=$count2[0]['count(*)'];
            }

        }


        $totalPage = ceil($count/$listPages);

        $data['current_page'] = $p;
        $data['total_page'] =$totalPage;
        $data['page_num'] = $page_size;
        $data['total_num'] = $count;
        $data['data'] = $list;

        return $data;
    }

    /**
     * 系统消息--收件箱
     */
    public function systemList($page,$page_size,$member_id,$user_id){
        //查询用户注册时间
        $create_time=Db::name('member')->where('member_id',$member_id)->value('create_time');

        $p = $page;
        $listPages = $page_size;
        $page = ($p-1)*$listPages;

        $sql = "SELECT `m_id`,`member_id`,`title`,`create_time`,`content`,`msg_type`,
(SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id  ) as is_read FROM `mm_message` m

WHERE   `create_time` > ".$create_time." AND (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0

AND ";
        $sql .= " (`object_type` = 1  OR (`object_type`=2 and FIND_IN_SET(". $member_id.",object_arr) ) and `member_id` =".$user_id;

        $sql .= " ) and class_type= 14 ";
        $sql .= " ORDER BY `create_time` DESC limit $page,$listPages";

        $sql_count = "SELECT count(*) FROM `mm_message` m
WHERE   `create_time` >".$create_time." AND  (SELECT COUNT(um.id) FROM mm_message_user um WHERE `member_id` =".$member_id." and um.mes_id = m.m_id and is_delete =1 )=0
AND ";
        $sql_count .= " (`object_type` = 1  OR (`object_type`=2 and FIND_IN_SET(". $member_id.",object_arr) ) and `member_id` =".$user_id;

        $sql_count .= ") and class_type= 14 ";
        //dump($sql_count);

        //查询未读的总条数
        $sql_count2 = "SELECT count(*) FROM `mm_message` m
        WHERE  `create_time` >".$create_time." 
        AND  (`object_type` = 1  OR (`object_type`=2 and FIND_IN_SET(". $member_id.",object_arr)) 
        and `member_id` =".$user_id ;
        $sql_count2 .= ") AND  (SELECT COUNT(um.id) FROM mm_message_user um 
            WHERE um.member_id =".$member_id." AND um.mes_id = m.m_id AND (um.is_delete = 1 OR um.is_read =1)  )=0
            and class_type = 14" ;

        $count2 = Db::query($sql_count2);

        $count = Db::query($sql_count);
        $count = $count[0]['count(*)'];
        $list =  Db::query($sql);

        //echo db()->getLastSql(); exit;
        foreach ($list as $k=>&$v){
            $user=Db::name('member')
                ->where('member_id',$v['member_id'])
                ->find();
            if(empty($user)){
                $v['nickName']='';
                $v['avatarUrl']='';
            }else{
                $v['nickName']=$user['nickName'];
                $v['avatarUrl']=$user['avatarUrl'];
            }
            //判断用户是否为直推，间推
            if($user['uid_1']==$member_id){
                $v['user_type']=1;//直推
            }elseif ($user['uid_2']==$member_id){
                $v['user_type']=2;//间推
            }else{
                $v['user_type']=3;//其他
            }

        }
        $totalPage = ceil($count/$listPages);

        $data['current_page'] = $p;
        $data['total_page'] =$totalPage;
        $data['page_num'] = $page_size;
        $data['total_num'] = $count;
        $data['data'] = $list;
        $data['count2'] = $count2[0]['count(*)'];

        return $data;
    }

}